/**
 * API常量
 */
var HOST = 'http://139.196.236.231:8070/';
var api = {
	user: {
		login: HOST + 'user/login',
		getauthcode: HOST + 'user/getauthcode',
		checkauthcode: HOST + 'user/checkauthcode',
		setpwd: HOST + 'user/changepwd',
		updateheadportrait: HOST + 'user/updateheadportrait',
		updateuserinfo: HOST + 'user/updateuserinfo',
	},
	station: {
		getstationlist: HOST + 'station/getstationlist',
		getstationdetail: HOST + 'station/getstationdetail',
		createorder: HOST + 'order/createorder',
	},
	order: {
		getorderlist: HOST + 'order/getorderlist',
		getorderdetail: HOST + 'order/getorderdetail',
	},
	product: {
		getproductlist: HOST + 'product/getproductlist',
	}
};

var animation = {
	popIn: 'pop-in',
	popOut: 'pop-out',
	slideInRight: 'slide-in-right',
	slideOutRight: 'slide-out-right',
	slideInBottom: 'slide-in-bottom',
	slideOutBottom: 'slide-out-bottom',
}

/*
 * message常量
 */
var msg = {
	TITLE: '油多多',
	NETWORK_IS_UNAVAILABLE: "网络异常，请检查您的网络设置",
	LOAD_DATA_FAIL: '数据加载失败，请稍后重试',
	AUTH_EXPIRED: '您的登录已过期，请重新登录',
};

/*
 * 封装常用的打开窗口，一般只需传入url及id
 * 默认显示等待框，默认不自动显示
 */
function openPage(url, id, extraObj, styleObj, showObj, waitObj) {
	showObj = showObj || {
		autoShow: false
	};
	waitObj = waitObj || {
		autoShwo: true,
		title: '请稍等...'
	}; // 默认显示等待框
	mui.openWindow({
		url: url,
		id: id,
		styles: styleObj,
		extras: extraObj,
		show: showObj,
		waiting: waitObj,
	})
}

function showPage(wv, aniShow, closeWaiting, duration) {
	if (tool.isEmptyVal(wv)) {
		console.log('webview为空');
		return;
	}
	if (tool.isString(wv)) {
		wv = plus.webview.getWebviewById(wv);
	}
	if (mui.os.android) aniShow = aniShow || animation.slideInRight;
	if (mui.os.ios) duration = duration || 300;
	wv.show(aniShow, duration);
	closeWaiting = typeof(closeWaiting) === "undefined" ? true : closeWaiting; // 默认要关闭
	if (closeWaiting) plus.nativeUI.closeWaiting();
}

/*
 * 工具类
 */
var tool = {
	isEmptyVal: function(val) {
		if (val === null || typeof(val) === 'undefined' || val === '')
			return true;

		return false;
	},
	isFunction: function(f) {
		return Object.prototype.toString.call(f) === "[object Function]";
	},
	isObject: function(o) {
		return Object.prototype.toString.call(o) === "[object Object]";
	},
	isString: function(s) {
		return Object.prototype.toString.call(s) === "[object String]";
	}
};

/* 
 * 保存数据
 * 注：目前使用h5的localStorage, 只能非跨域下工作
 */
function cache(key, val) {
	if (key === 'clear') {
		window.localStorage.clear();
	} else if (val === null) {
		window.localStorage.removeItem(key);
	} else if (val) {
		window.localStorage[key] = val;
	} else {
		return window.localStorage[key];
	}
}

/*
 * 数据访问
 */
var persistent = {
	uid: function() {
		return cache('uid');
	},
	utoken: function() {
		return cache('utoken');
	},
	uinfo: function() {
		var usrInfo = cache('uinfo');
		if (tool.isEmptyVal(usrInfo)) {
			return null;
		}
		return JSON.parse(usrInfo);
	},
}

var ajaxStatus = {
	OK: 200,
	ERROR: 300,
	FAIL_AUTH: 400,
	REFUSE: 500,
};

/*
 * 封装ajax
 */
var ajax = {
	getAuthHeader: function() {
		return persistent.uid() + ',' + persistent.utoken() + ',' + plus.device.uuid + ',' + 'sign';
	},
	post: function(url, paramObj, suc, wait, comp, err) {
		// 检测网络是否可用
		var network = plus.networkinfo.getCurrentType();
		if (network === plus.networkinfo.CONNECTION_UNKNOW ||
			network === plus.networkinfo.CONNECTION_NONE) {
			mui.alert(msg.NETWORK_IS_UNAVAILABLE, msg.TITLE, 'OK');
			if (tool.isFunction(err)) err();
			if (tool.isFunction(comp)) comp();
			return;
		}

		if (tool.isObject(url)) {
			paramObj = url.paramObj;
			suc = url.suc;
			wait = url.wait;
			comp = url.comp;
			err = url.err;
			url = url.url;
		}

		// 显示等待框
		// if(typeof(wait)==="undefined") wait=true; // 设置默认是否显示
		wait = wait === null ? false : wait;
		if (wait) {
			plus.nativeUI.showWaiting();
		}
		paramObj = paramObj || {};
		// uri编码
		for (var k in paramObj) {
			var v = paramObj[k];
			if (tool.isString(v)) {
				v = v.replace(/\\/g, '\\\\');
				paramObj[k] = encodeURIComponent(v);
			}
		}

		var headerObj = {};
		headerObj.Authorization = this.getAuthHeader();

		// 发送请求
		mui.ajax(url, {
			type: 'POST',
			timeout: 10000,
			data: paramObj,
			dataType: 'json',
			headers: headerObj,
			success: function(data, textStatus, xhr) {
				if (data.StatusCode === ajaxStatus.OK) {
					if (tool.isFunction(suc)) suc(data, textStatus, xhr);
				} else if (data.StatusCode === ajaxStatus.ERROR) {
					var errMsg = data.Msg || msg.LOAD_DATA_FAIL;
					plus.nativeUI.toast(errMsg);
					if (tool.isFunction(err)) err();
				} else if (data.StatusCode === ajaxStatus.FAIL_AUTH) {
					plus.nativeUI.toast(msg.AUTH_EXPIRED);
					mui.openWindow(plus.io.convertAbsoluteFileSystem('_www/page/user/login.html'), 'login', null);
					if (tool.isFunction(err)) err();
				} else if (data.StatusCode === ajaxStatus.REFUSE) {
					// TODO 待完善
					plus.nativeUI.toast('拒绝访问');
				}
			},
			error: function(xhr, type) {
				plus.nativeUI.toast(msg.LOAD_DATA_FAIL + "(" + type + ")");
				if (tool.isFunction(err)) err();
			},
			complete: function() {
				if (wait) plus.nativeUI.closeWaiting();
				if (tool.isFunction(comp)) comp();
			}
		});
	},
};

/*
 * 用户相关的方法及属性
 */
var user = {
	login: function(uname, pwd, suc) {
		ajax.post(api.user.login, {
			Username: uname,
			Password: pwd,
		}, function(data) {
			data = data.Data;
			// 缓存用户信息
			console.log('登录成功，uid: ' + data.UserID);
			cache('uid', data.UserID);
			cache('utoken', data.Token);
			cache('uinfo', JSON.stringify(data));
			// 回调
			suc();
		}, true);
	},
	// Reg/Psw
	getauthcode: function(type, tel, suc) {
		ajax.post(api.user.getauthcode, {
			Type: type,
			Telephone: tel
		}, suc, true);
	},
	checkauthcode: function(code, tel, type, suc) {
		ajax.post(api.user.checkauthcode, {
			Authcode: code,
			Telephone: tel,
			Type: type,
		}, suc);
	},
	updateuserinfo: function(att, value, suc) {
		ajax.post(api.user.updateuserinfo, {
			Attribute: att,
			Value: value
		},  function(data) {
			suc(data.StatusCode)
		}, true);
	},
	updateheadportrait: function(portrait, suc) {
		ajax.post(api.user.updateheadportrait, {
			File: portrait
		}, function(data) {
			suc(data.Data);
		}, true);
	},
	// Reg/Forget/Modify
	setpwd: function(tel, psw, type, suc) {
		ajax.post(api.user.setpwd, {
			Telephone: tel,
			Password: psw,
			Type: type
		}, function(data) {
			// 缓存用户信息
			cache('uid', data.UserID);
			cache('utoken', data.Token);
			cache('uinfo', JSON.stringify(data));
			// 回调
			suc();
		});
	}
};

var station = {
	getlist: function(keyword, latitude, longitude, pageSize, curpage, suc, comp) {
		ajax.post(api.station.getstationlist, {
			KeyWord: keyword,
			Latitude: latitude,
			Longitude: longitude,
			PageSize: pageSize,
			CurPage: curpage
		}, function(data) {
			suc(data.Data);
		}, false, comp);
	},
	getdetail: function(id, suc, comp) {
		ajax.post(api.station.getstationdetail, {
			Id: id
		}, function(data) {
			suc(data.Data);
		}, false, comp)
	},
	createorder: function(UserId, StationId, ProductId, Telephone, suc, err) {
		ajax.post(api.station.createorder, {
			UserId: UserId,
			StationId: StationId,
			ProductId: ProductId,
			Telephone: Telephone,
		}, function(data) {
			suc(data.Data);
		}, false, null, err);
	}
};

var order = {
	getOrderList: function(paramObj, suc, comp, err) {
		ajax.post(api.order.getorderlist, paramObj, function(data) {
			suc(data.Data);
		}, false, comp, err);
	},
	getOrderDetail: function(paramObj, suc, comp, err) {
		ajax.post(api.order.getorderdetail, paramObj, function(data) {
			suc(data.Data);
		}, false, comp, err);
	}
};

var product = {
	getlist: function(suc, comp) {
		ajax.post(api.product.getproductlist, null, function(data) {
			suc(data.Data);
		}, false, comp);
	}
}

var ui = {
	setScroll: function(scrollWrapper, scroll, refreshEvt, moreEvt) {
		//阻尼系数
		var deceleration = mui.os.ios ? 0.003 : 0.0009;
		var scroller = mui(scrollWrapper).scroll({
			bounce: false,
			indicators: true, //是否显示滚动条
			deceleration: deceleration
		});
		var initObj = {};
		if (refreshEvt) initObj.down = {
			callback: function() {
				setTimeout(function() {
					refreshEvt();
				}, 100);
			}
		};
		if (moreEvt) initObj.up = {
			callback: function() {
				setTimeout(function() {
					moreEvt();
				}, 100);
			}
		};

		var puller = mui(scroll).pullToRefresh(initObj);
		return {
			scroller: scroller,
			puller: puller
		};
	}
}